package com.tckj.boot.modules.domain.sys.user.application;

import com.tckj.boot.common.utils.IpUtils;
import com.tckj.boot.modules.domain.sys.role.model.Role;
import com.tckj.boot.modules.domain.sys.role.model.RoleRepository;
import com.tckj.boot.modules.domain.sys.user.model.User;
import com.tckj.boot.modules.domain.sys.user.model.UserDetailsInfo;
import com.tckj.boot.modules.domain.sys.user.model.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @ClassName UserService
 * @Description
 * @Author icodebug
 * @Date 19-6-8 下午7:11
 */
@Service
@AllArgsConstructor
public class UserService {

    private UserRepository repository;
    private RoleRepository roleRepository;
    private PasswordEncoder passwordEncoder;

    public User save(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
//        user.getDetails().setNickname(user.getUsername());
        List<Role> roles = roleRepository.findAllById(user.getRoleSet().stream().map(Role::getId).collect(Collectors.toList()));
        user.setRoleSet(new HashSet<>(roles));
        return repository.save(user);
    }

    public User wxAddUser(String openId,String avatarUrl,Byte gender,String nickName,String ip,String sessionKey) {

        Optional<User> userOptional = repository.findByWeixinOpenid(openId);
        User user = null;
        if (!userOptional.isPresent()) {
            user = new User();
            user.setPassword(openId);
            user.setWeixinOpenid(openId);
            user.setUsername(openId);
            UserDetailsInfo detailsInfo = new UserDetailsInfo();
            detailsInfo.setAvatar(avatarUrl);
            detailsInfo.setGender(gender);
            detailsInfo.setNickname(nickName);
            user.setDetails(detailsInfo);
            user.setLastLoginTime(new Date());
        } else {
            user = userOptional.get();
        }
        user.setLastLoginTime(new Date());
        user.setLastLoginIp(ip);
        user.setSessionKey(sessionKey);

        user.setRoleSet(new HashSet<>(roleRepository.findByName("CUSTOM")));
        return repository.save(user);
    }

    public User update(User user){
        return repository.saveAndFlush(user);
    }

    public Optional<User> findByUserName(String userName){
        return repository.findByUsername(userName);
    }

    public Optional<User> findByWeixinOpenid(String weixinOpenid){
        return repository.findByWeixinOpenid(weixinOpenid);
    }

    public User findById(Long id){
        return repository.findById(id).get();
    }

}
